package com.easydisk.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easydisk.admin.common.AdminConstant;
import com.easydisk.admin.common.PageInfoResult;
import com.easydisk.admin.common.PageInfoResultBuilder;
import com.easydisk.admin.dto.UserDto;
import com.easydisk.admin.model.req.AddUserReq;
import com.easydisk.admin.model.req.DelUserReq;
import com.easydisk.admin.model.req.LoginReq;
import com.easydisk.admin.model.vo.UserInfoVO;
import com.easydisk.admin.pojo.Role;
import com.easydisk.admin.pojo.User;
import com.easydisk.admin.pojo.UserAndRole;
import com.easydisk.admin.service.RoleService;
import com.easydisk.admin.service.UserAndRoleService;
import com.easydisk.admin.service.UserService;
import com.easydisk.constant.UserConstant;
import com.easydisk.response.R;
import com.easydisk.common.util.UserIdUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author word
 */
@RestController
@RequestMapping("/admin/user")
public class AdminController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserAndRoleService userAndRoleService;
    @Autowired
    private RoleService roleService;
    @Resource
    private PasswordEncoder passwordEncoder;
    /**
     * 管理员查看所有用户列表*
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/list")
    public R<PageInfoResult> page(@RequestParam(defaultValue = "") String name,
                                  @RequestParam(required = false) Integer page,
                                  @RequestParam(required = false) Integer pageSize){


        PageHelper.startPage(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //做过滤条件，根据名字模糊查询用户表
        queryWrapper.like(name != null, User::getUsername, name)
                .eq(User::getStatus, UserConstant.UserStatusEnum.YES.getCode());
        //将查询到的所有用户放进pageInfo,还没有角色信息
        List<User> userList = userService.list(queryWrapper);
        //创建具有角色信息的分页构造器
        Page<UserDto> dtoPage = new Page<>(page, pageSize);
        //复制pageInfo信息给dtoPage，除了records
        BeanUtils.copyProperties(userList,dtoPage,"records");
        List<UserDto> list = userList.stream().map((item)->{
            UserDto userDto = new UserDto();
            //将item信息复制给userDto
            BeanUtils.copyProperties(item,userDto,"password");

            userDto.setId(item.getId());
            userDto.setUpdateTime(item.getUpdateTime());
            userDto.setCreateTime(item.getCreateTime());

            userDto.setDiskMaxSize(item.getDiskMaxSize() + "G");
            //构建条件构造器
            LambdaQueryWrapper<UserAndRole> wrapper = new LambdaQueryWrapper<>();
            //通过userID获取角色userRole信息
            wrapper.eq(UserAndRole::getUserId,item.getId());
            UserAndRole userAndRole = userAndRoleService.getOne(wrapper);

            //在通过userRoleId获取Role信息
            Role role = roleService.getById(userAndRole.getRoleId());
            //将角色和描述赋值给userDto
            userDto.setRoleName(role.getRoleName());
            userDto.setDescription(role.getDescription());
            return userDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        PageInfoResult pageInfoResult = PageInfoResultBuilder.create()
                .withPage(page)
                .withPageSize((int) dtoPage.getSize())
                .withPages((int) dtoPage.getPages())
                .withIsLastPage(dtoPage.getPages() == page)
                .withTotal(dtoPage.getTotal())
                .withList(dtoPage.getRecords()).build();
        return R.success("获取用户列表成功",pageInfoResult);
    }

    /**
     * 根据id实现某个用户同时删除
     * 不能删除管理员和本人
     * @ userId 要删除的用户id
     * @ id 当前请求用户id
     * @return
     */
    @DeleteMapping("/delete")
    public R delete(@Validated @RequestBody DelUserReq delUserReq) {

        Long userId = delUserReq.getDelUserId();
        Long id = delUserReq.getCurrentUserId();

        //构建条件构造器
        LambdaQueryWrapper<UserAndRole> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();

        //通过userId查询userRoleId
        queryWrapper.eq(UserAndRole::getUserId,userId);
        UserAndRole userAndRole = userAndRoleService.getOne(queryWrapper);
        if(userAndRole != null){
            wrapper.eq(Role::getId,userAndRole.getRoleId());
            Role role = roleService.getOne(wrapper);
            //不能删除本人
            if(id.equals(userId)){
                return R.fail("不能删除自己");
            }
            //判断此用户是否为管理员
            if("admin".equals(role.getRoleName())){
                return R.fail("不能删除管理员");
            }
            //根据id删除User表的用户信息(逻辑删除)
            userService.update(new UpdateWrapper<User>().eq("\"id\"", userId)
                    .set("\"status\"", UserConstant.UserStatusEnum.NO.getCode()));
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }



    @PostMapping("/login")
    public R login(@RequestBody LoginReq loginReq) {
        List<User> userList = userService.list(new QueryWrapper<User>()
                .eq("username", loginReq.getUsername()));
        if (CollectionUtils.isEmpty(userList)) {
            return R.fail("账号错误");
        }
        User user = userList.get(0);
        //验证管理员密码
        if (!passwordEncoder.matches(loginReq.getPassword(),user.getPassword())) {
            return R.fail("密码错误");
        }
        //验证用户为管理员
        UserAndRole userAndRole = userAndRoleService.getOne(new QueryWrapper<UserAndRole>()
                .eq("user_id",user.getId()));
        Role role = roleService.getOne(new QueryWrapper<Role>()
                .eq("id", userAndRole.getRoleId()));
        String roleName = role.getRoleName();
        if(!"admin".equals(roleName)){
            return R.fail("非管理员不能登陆");
        }
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setUserId(String.valueOf(user.getId()));
        userInfoVO.setUsername(user.getUsername());
        return R.data(userInfoVO);
    }

    /**
     * 新增用户
     */
    @Transactional
    @PostMapping("/add")
    public R<String> addUser(@Validated  @RequestBody AddUserReq addUserReq){
        // 判断当前登录用户角色
        List<UserAndRole> userAndRoles = userAndRoleService
                .list(new QueryWrapper<UserAndRole>().eq("user_id", addUserReq.getUserId()));
        if (CollectionUtils.isEmpty(userAndRoles)) {
            return R.fail("非管理员，无权限新增用户");
        }
        boolean isAdmin = false;
        for (UserAndRole userAndRole : userAndRoles) {
            Role role = roleService.getById(userAndRole.getRoleId());
            if (AdminConstant.ADMIN.equals(role.getRoleName())) {
                isAdmin = true;
                break;
            }
        }
        if (!isAdmin) {
            return R.fail("非管理员，无权限新增用户");
        }
        userService.addUser(addUserReq);
        return R.success("添加成功");
    }

}